﻿using RoadQualityEvalAPI.Models;
using RoadQualityEvaluatorData.Domain.Entities;
using RoadQualityEvaluatorData.DomainServices.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace RoadQualityEvalAPI.Helpers
{
    public class AccountHelper
    {
        private UserRepository _userRepo;

        public AccountHelper()
        {
            this._userRepo = new UserRepository();
        }

        public bool ValidLogin(string username, string password)
        {
            // hash password using same algorithm as client
            string hash = password;


            // check if there exists such a user
            var user = _userRepo.GetUserByUsername(username);
            if (user != null)
            {
                string roles = "";
                foreach (var x in user.UserRoles)
                {
                    roles += x.RoleName;
                    roles += ",";
                }
                roles = roles.Remove(roles.Length - 1);

                if (user.HashedPassword.Equals(hash))
                {
                    // create login cookie with authenticated user
                    FormsAuthenticationTicket loginTicket = new FormsAuthenticationTicket(
                            1,
                            user.Username,
                            DateTime.Now,
                            DateTime.Now.AddHours(1),
                            false,
                            roles,
                            String.Empty
                        );

                    string encryptedTicket = FormsAuthentication.Encrypt(loginTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                    HttpContext.Current.Response.Cookies.Add(cookie);

                    return true;
                }
            }

            return false;
        }


        public void RegisterNewUser(RegisterModel model)
        {
            // hash password first
            string hash = model.Password;

            _userRepo.Add(new User()
            {
                CreatedAt = DateTime.Now,
                Email = model.EmailAddress,
                Info = model.Information,
                Username = model.UserName,
                HashedPassword = hash
            });
        }

        
        

    }
}